<template>
    <div style="border: 1px solid #ccc">
        <toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :default-config="toolbarConfig"
            :mode="mode"
        />
        <editor
            v-model="props.modelValue"
            style="height: 500px; overflow-y: hidden, width=100％"
            :default-config="editorConfig"
            :mode="mode"
            @on-created="handleCreated"
            @on-change="handleChange"
        />
    </div>
</template>
<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css

import type { IDomEditor } from '@wangeditor/editor';
import { IEditorConfig } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import { onBeforeUnmount, onMounted, ref, shallowRef, watch } from 'vue';

const props = defineProps({
    mode: {
        type: String,
        default: 'default',
    },
    modelValue: {
        type: String,
        default: '',
    },
    placeholder: {
        type: String,
        default: '请输入内容...',
    },
});
const emits = defineEmits(['update:modelValue']);
const valHtml = ref();
watch(
    () => props.modelValue,
    (val) => {
        valHtml.value = val;
    },
    { immediate: true, deep: true },
);

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtml = ref('<p>hello</p>');

// 模拟 ajax 异步获取内容
onMounted(() => {
    setTimeout(() => {
        valueHtml.value = '<p>模拟 Ajax 异步设置内容</p>';
    }, 1500);
});

const toolbarConfig = {};
const editorConfig = { placeholder: props.placeholder };

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

const handleCreated = (editor) => {
    editorRef.value = editor; // 记录 editor 实例，重要！
};
/**
 * 编辑器发生变化，动态绑定到v-model
 * @param editor
 */
const handleChange = (editor: IDomEditor) => {
    emits('update:modelValue', editor.getHtml());
};
</script>
